package com.spr.gw.service.impl;

import com.spr.gw.common.EnumCode;
import com.spr.gw.common.ResponseCode;
import com.spr.gw.common.ResultBean;
import com.spr.gw.entity.User;
import com.spr.gw.mapper.UserMapper;
import com.spr.gw.service.SystemLogService;
import com.spr.gw.service.UserService;
import com.spr.gw.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by lsy
 * on 2017/10/20 17:21.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SystemLogService logService;

    public ResultBean login(User user, HttpServletRequest request){
        if(StringUtils.isEmpty(user.getUsername())){
            return ResultBean.createByCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        if(StringUtils.isEmpty(user.getPassword())){
            return ResultBean.createByCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        user.setPassword(MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
        List<User> users = userMapper.select(user);
        if(users != null && users.size() > 0){
            //登录成功
            User loginUser = users.get(0);
            HttpSession session = request.getSession();
            loginUser.setPassword(null);
            session.setAttribute(EnumCode.LOGIN_USER.getValue(), loginUser);
            logService.recordLog(request, "登录系统", "【登录成功】"+loginUser.getUsername());
            return ResultBean.createBySuccess(loginUser);
        }
        return ResultBean.createByCodeMessage(ResponseCode.USER_NOT_EXIST.getCode(),ResponseCode.USER_NOT_EXIST.getDesc());
    }

    @Override
    public ResultBean logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute(EnumCode.LOGIN_USER.getValue());
        session.removeAttribute(EnumCode.LOGIN_USER.getValue());
        if(loginUser != null)
            logService.recordLog(request, "退出系统", "【退出系统成功】" + loginUser.getUsername());
        return ResultBean.createBySuccess("退出系统成功");
    }
}
